import configs
import time
from .speech_utils import speak
from utils import service_functions
from ..corpus_languages import Class_corpus_language
from template.singleton import Singleton
import os


class Сommunication(Singleton):
    def settings(self):
        self.__menu_list = configs.default_modul
        self.obj_corpus_language = Class_corpus_language()
        self.__modul_value = []
        self.message_timer = 60
        self.__index_waiting = 0

    def __voice(self, messege: str) -> None:
        if configs.stop_sr.qsize() >= 5:
            configs.stop_sr.queue.clear()
        else:
            pass
        for word in configs.dict_value_str_voice["del_word"]:
            messege = messege.replace(word, " ")
        configs.stop_sr.put("False")
        speak(messege)
        configs.stop_sr.put("True")

    def _print_message(self, messege: str) -> None:
        print(f"{configs.name_voice_help.capitalize()}: {messege}")

    def notifications(self, mess):
        # Уведомления на рабочий стол Linux
        os.system(f"notify-send {mess}")

    def __write_file(self, str_messege: str) -> None:
        service_functions.write_meta_data(str_messege, "voice_file.txt")

    def messege_menu(self, var_out_stream: str) -> None:
        # !!!
        service_functions.write_meta_data(f"{var_out_stream}", "modul_message.txt")
        if not (var_out_stream in self.__modul_value) and var_out_stream != "clear":
            self.__menu_list.append(var_out_stream)
        elif var_out_stream == "clear":
            self.__menu_list.clear()
        else:
            pass

    def message(self, str_messege) -> None:
        str_messege = self.obj_corpus_language.corpus_lang(
            str_messege, configs.language_name
        )
        str_messege = str(str_messege)
        configs.comuniction_str_api = str_messege
        configs.speech_blocking = True
        for menu in self.__menu_list:
            if menu == "core_modul_voice":
                self.__voice(str_messege)
            elif menu == "core_modul_print_message":
                self._print_message(str_messege)
            elif menu == "core_modul_write_file":
                self.__write_file(str_messege)
            elif menu == "core_modul_notifications":
                self.notifications(str_messege)
            else:
                pass
        self.buff_message(str_messege)
        configs.speech_blocking = False

    def buff_message(self, str_messege):
        # Добавить запись в SQL !!!
        service_functions.write_meta_data(str_messege, "modul_message.txt")
        if len(configs.buff_list_mess_comm["mess"]) >= configs.buff_mess_comm_count:
            configs.buff_list_mess_comm = {"mess": [], "data": []}
        configs.buff_list_mess_comm["mess"].append(str_messege)
        configs.buff_list_mess_comm["data"].append(time.time())
